package engine.resource.inputfile;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import engine.game.level.LevelMap;
import engine.game.level.tiles.Tile;
import engine.resource.Resources;

public class LevelMapConfigFile extends ConfigFile {

    private LevelMap map;

    public LevelMapConfigFile(String path) {
        super(path);
    }

    public LevelMapConfigFile(File file) {
        super(file);
    }

    public void readData() {
        super.readData();

        Map<Integer, Tile> key = new HashMap<>();
        Tile[][] tiles = null;

        try {
            ConfigNode keyNode = nodes.get("KEY");
            key = getKeyFrom(keyNode);

            ConfigNode mapNode = nodes.get("MAP");
            tiles = getTilesFrom(key, mapNode);

            map = new LevelMap(tiles, filePath);
        }
        catch (Exception e) {
            logger.log(e);
            e.printStackTrace();
        }
    }

    private Map<Integer, Tile> getKeyFrom(ConfigNode node) {
        Map<Integer, Tile> key = new HashMap<>();
        int curNum = 0;

        while (node.hasValue(curNum + "")) {
            key.put(curNum, Resources.getTile(node.value(curNum + "")));
            curNum++;
        }

        return key;
    }

    private Tile[][] getTilesFrom(Map<Integer, Tile> key, ConfigNode node) {
        ArrayList<Tile[]> tiles = new ArrayList<>();
        Tile[][] returnTiles = null;

        try {
            int lineNum = 0;
            while (node.hasValue("LINE" + lineNum)) {
                String[] sArr = node.value("LINE" + lineNum).split("\t");
                Tile[] lineTiles = new Tile[sArr.length];

                for (int i = 0; i < sArr.length; i++) {
                    int tileNum = Integer.parseInt(sArr[i]);
                    lineTiles[i] = key.get(tileNum);
                }

                tiles.add(lineTiles);
                lineNum++;
            }

            returnTiles = new Tile[tiles.get(0).length][tiles.size()];
            for (int x = 0; x < tiles.get(0).length; x++) {
                for (int y = 0; y < tiles.size(); y++) {
                    returnTiles[x][y] = tiles.get(y)[x];
                }
            }
        }
        catch (Exception e) {
            logger.log(e);
            e.printStackTrace();
        }

        return returnTiles;
    }

    public LevelMap levelMap() {
        return map;
    }
}
